from datetime import timedelta
from flask import Blueprint, request
from flask_jwt_extended import create_access_token
from app.models.user import User
from app.utils.response import success_response, error_response

get_token_bp = Blueprint('get_token', __name__)

@get_token_bp.route('/token', methods=['POST'])
def get_token_for_testing():
    """
    [测试专用] 获取用户Token
    ---
    tags:
      - 调试工具
    summary: 为指定用户ID生成一个用于测试的JWT Token
    description: 此接口仅用于开发和测试环境，请勿在生产环境暴露。
    parameters:
      - in: body
        name: body
        required: true
        schema:
          type: object
          required:
            - user_id
          properties:
            user_id:
              type: integer
              description: 需要生成Token的用户ID (例如, 1 代表管理员)
              example: 1
            days_valid:
              type: integer
              description: "Token有效天数。传 0 表示永不过期。默认为 30。"
              example: 30
    responses:
      200:
        description: Token生成成功
        schema:
          type: object
          properties:
            message:
              type: string
              example: Token generated successfully.
            data:
                type: object
                properties:
                    user_id:
                      type: integer
                    token:
                      type: string
                    expires:
                      type: string
      400:
        description: 缺少 `user_id`
      404:
        description: 用户未找到
    """
    if not request.is_json:
        return error_response("请求体必须是JSON格式", code=415)

    data = request.get_json()
    user_id = data.get('user_id')
    days_valid = data.get('days_valid', 30)

    if not user_id:
        return error_response("必须提供 `user_id`")

    user = User.query.get(user_id)
    if not user:
        return error_response(f"ID为 {user_id} 的用户不存在", code=404)
        
    expires_delta = False
    if days_valid > 0:
        expires_delta = timedelta(days=days_valid)

    access_token = create_access_token(identity=str(user.id), expires_delta=expires_delta)
    
    return success_response({
        'user_id': user.id,
        'token': access_token,
        'expires': 'non-expiring' if not expires_delta else f'{days_valid} days'
    }) 